<script setup>
import Peer from 'peerjs'
import { ref, onMounted } from 'vue'
const myMsg = ref('')
const myVideo = ref(null)
const peer = new Peer()
let peerId = null
let remotePeerId = null
let conn = null
peer.on('open', (id) => {
  console.log(id)
  peerId = id
})
const requestPeer = () => {
  localStorage.setItem('peerId', peerId)
}
// 监听媒体连接
peer.on('call', (MediaConnection) => {
  console.log('call', MediaConnection)
  conn = MediaConnection
  conn.on('stream', (stream) => {
    myVideo.value.srcObject = stream
  })
})
// 监听被对方连接的事件
peer.on('connection', (connObj) => {
  // 保存接受方的id
  localStorage.setItem('receiveId', connObj.peer)
  remotePeerId = connObj.peer
  conn = peer.connect(remotePeerId)
  console.log('我被连接啦')
  // 监听接收消息
  connObj.on('data', (data) => {
    console.log('收到接受方消息', data)
  })
  connObj.on('icecandidate', (candidate) => {
    console.log(111, candidate)
  })
})
// 发送数据
const sendData = () => {
  conn.send(myMsg.value)
}
// 发送视频
const sendVideo = () => {
  console.log(remotePeerId, localMediaStream)
  const mediaConnection = peer.call(remotePeerId, localMediaStream)
  mediaConnection.on('stream', (remoteStream) => {
    console.log(1, remoteStream)
  })
}
let localVideo = null
const mouseMove = (event) => {
  // console.log(event.offsetX, event.offsetY)
}
const mouseDown = (event) => {
  console.log('down', event.button === 0 ? 'left' : 'right')
}
const mouseUp = (event) => {
  console.log('up', event.button === 0 ? 'left' : 'right')
}
const mouseEnter = () => {
  console.log('enter')
}
const mouseLeave = () => {
  console.log('leave')
}
const Wheel = (event) => {
  console.log('Wheel', event.deltaY)
}
onMounted(async () => {
  localVideo = document.getElementById('localVideo')
  localVideo.addEventListener('mousemove', mouseMove)
  localVideo.addEventListener('mousedown', mouseDown)
  localVideo.addEventListener('mouseup', mouseUp)
  localVideo.addEventListener('mouseenter', mouseEnter)
  localVideo.addEventListener('mouseleave', mouseLeave)
  localVideo.addEventListener('wheel', Wheel)
  initVideo()
  const devices = await navigator.mediaDevices.enumerateDevices()
  console.table(1, devices)
})
let localMediaStream = null
const initVideo = async () => {
  localMediaStream = await navigator.mediaDevices.getUserMedia({
    video: { width: 500, height: 400 },
    audio: true
  })
  // 成功获取本地摄像头流
  // 在这里处理流，例如显示在页面上
  // 连接 PeerJS
  localVideo.srcObject = localMediaStream
  localVideo.addEventListener('loadedmetadata', () => {
    localVideo.play()
  })
}

const clearListener = () => {
  localVideo.removeEventListener('mousemove', mouseMove)
}
const takeScreen = () => {
  const localVideo = document.getElementById('localVideo')
  const screenshotCanvas = document.getElementById('screenshotCanvas')
  const context = screenshotCanvas.getContext('2d')

  // 设置 canvas 尺寸与视频一致
  screenshotCanvas.width = localVideo.videoWidth
  screenshotCanvas.height = localVideo.videoHeight

  // 在 canvas 上绘制当前视频帧
  context.drawImage(localVideo, 0, 0, localVideo.videoWidth, localVideo.videoHeight)

  // 获取图像数据
  const imageData = screenshotCanvas.toDataURL('image/png')

  // 创建一个新的图像元素，并将数据赋给它
  const img = new Image()
  img.src = imageData

  // 将图像追加到文档中，或者进行其他处理
  document.body.appendChild(img)
}
const shareDesktop = async () => {
  try {
    const desktopStream = await navigator.mediaDevices.getDisplayMedia()

    const desktopShareVideo = document.querySelector('#desktop-share-video')
    desktopShareVideo.srcObject = desktopStream
    desktopShareVideo.addEventListener('loadedmetadata', () => desktopShareVideo.play())
  } catch (err) {
    console.error(err)
  }
}
</script>
<template>
  <el-button @click="requestPeer">连接请求</el-button>
  <el-input v-model="myMsg" />
  <el-button @click="sendData">发送请求</el-button>
  <video id="localVideo" class="my-video" ref="myVideo" autoplay playsinline></video>
  <canvas id="screenshotCanvas" style="display: none"></canvas>
  <video autoplay playsinline id="desktop-share-video"></video>
  <el-button @click="initVideo">连接摄像头</el-button>
  <el-button @click="takeScreen">截图</el-button>
  <el-button @click="clearListener">清除监听</el-button>
  <el-button @click="shareDesktop">录制功能</el-button>
  <el-button @click="sendVideo">发送视频</el-button>
</template>

<style lang="scss" scoped>
.my-video {
  width: 640px;
  height: 480px;
  background-color: #ccc;
  cursor: pointer;
  object-fit: contain;
}
</style>
